package com.woniu.atms.controller.pre;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.woniu.atms.entity.G5Order;
import com.woniu.atms.entity.G5Ticket;
import com.woniu.atms.entity.G5TicketSite;
import com.woniu.atms.service.G5OrderService;
import com.woniu.atms.service.G5TicketService;
import com.woniu.atms.service.G5TicketSiteService;
import com.woniu.atms.util.Code;
import com.woniu.atms.util.ResponseResult;
import com.woniu.atms.vo.pre.order.OrderPageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张杰
 * @title: PreOrderController 用户订单管理
 * @projectName g5_atms
 * @description: TODO
 * @date 2022/1/17 15:06
 */
@Api(tags = "订单管理（前台）")
@RestController
@RequestMapping("/api/pre/v1/order")
public class PreOrderController {
    @Autowired
    private G5OrderService g5OrderService;
    @Autowired
    private G5TicketService g5TicketService;
    @Autowired
    private G5TicketSiteService g5TicketSiteService;

    /**
     * 按条件分页查询
     *
     * @param orderPageVO 分页查询视图（筛选条件,起始页,每页条数）
     * @return 返回统一响应
     */
    @ApiOperation(value = "订单展示", notes = "可分页、可多条件（没有条件则查所有）、订单号可以模糊，参数为订单分页查询视图")
    @RequestMapping("/list")
    public ResponseResult<PageInfo<G5Order>> queryByPage(@RequestBody @Validated OrderPageVO orderPageVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", orderPageVO.getG5Order().getId());
        map.put("orderNo", orderPageVO.getG5Order().getOrderNo());
        map.put("userId", orderPageVO.getG5Order().getUserId());
        map.put("createTime", orderPageVO.getG5Order().getCreateTime());
        map.put("payTime", orderPageVO.getG5Order().getPayTime());
        map.put("isOk", orderPageVO.getG5Order().getIsOk());
        map.put("isExit", orderPageVO.getG5Order().getIsExit());
        return new ResponseResult<>(this.g5OrderService.findByPage(map, orderPageVO.getPageNum(), orderPageVO.getPageSize()));
    }

    /**
     * 按条件分页查询
     * (可以通过订单号)
     *
     * @param orderPageVO 分页查询视图（筛选条件,起始页,每页条数）
     * @return 返回统一响应
     */
    @ApiOperation(value = "订单展示（主要按订单号）", notes = "可分页、可多条件（没有条件则查所有）、订单号可以模糊，参数为订单分页查询视图")
    @GetMapping("/order_info")
    public ResponseResult<PageInfo<G5Order>> orderInfo(@RequestBody OrderPageVO orderPageVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderNo", orderPageVO.getG5Order().getOrderNo());
        map.put("userId", orderPageVO.getG5Order().getUserId());
        return new ResponseResult<>(this.g5OrderService.findByPage(map, orderPageVO.getPageNum(), orderPageVO.getPageSize()));
    }

    /**
     * 通过订单编号查询单条数据
     *
     * @param g5Order 订单信息
     * @return 统一响应
     */
    @ApiOperation(value = "订单信息", notes = "通过订单编号查询单条数据，参数为订单信息")
    @RequestMapping("/orderNo")
    public ResponseResult<G5Order> orderNo(@RequestBody G5Order g5Order) {
        return new ResponseResult<>(this.g5OrderService.queryByOrderNo(g5Order.getOrderNo()));
    }

    /**
     * 订单删除
     *
     * @param g5Order 订单信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "订单删除", notes = "修改订删除，（逻辑删除只需修改状态），参数为订单信息")
    @PostMapping("/del")
    public ResponseResult<G5Order> del(@RequestBody G5Order g5Order) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", g5Order.getId());
        System.out.println(g5Order.getId());
        long o = g5OrderService.count(queryWrapper);
        G5Order o2 = g5OrderService.getOne(queryWrapper);
        if (o == 1 && o2.getIsExit().equals("y")) {
            g5Order.setIsExit("n");
            g5OrderService.update(g5Order);
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "该订单不存在！");
    }

    /**
     * 订单支付
     *
     * @param g5Order 订单信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "订单支付", notes = "修改订单状态，车票表状态，参数为订单信息")
    @RequestMapping("/pay")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<G5Order> pay(@RequestBody G5Order g5Order) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", g5Order.getId());
        long o = g5OrderService.count(queryWrapper);
        G5Order o2 = g5OrderService.getOne(queryWrapper);
        //订单状态改为y（x是未付款，y是已付款，n是退款,q是取消）
        if (o != 0 && "x".equals(o2.getIsOk())) {
            g5Order.setIsOk("y");
            g5Order.setPayTime(new Date());
            g5OrderService.update(g5Order);
            //修改车票为已付款(一个订单包含多个车票)
            List<G5Ticket> t2 = g5TicketService.queryByOrderId(o2.getId());
            G5Ticket g5Ticket = new G5Ticket();
            G5TicketSite g5TicketSite = new G5TicketSite();
            for (int i = 0; i < t2.size(); i++) {
                g5Ticket.setId(t2.get(i).getId());
                g5Ticket.setIsPay("y");
                g5TicketService.update(g5Ticket);
                //修改具体时间车票座位中间表的座位状态
                g5TicketSite.setId(t2.get(i).getTimeSeatId());
                g5TicketSite.setSiteStatus("n");
                g5TicketSiteService.update(g5TicketSite);
            }
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "请勿重复付款！");
    }

    /**
     * 订单取消
     *
     * @param g5Order 订单信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "订单取消", notes = "修改订单状态，车票表状态，具体时间查票座位中间表状态，参数为订单信息")
    @PostMapping("/cancel")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<G5Order> cancel(@RequestBody G5Order g5Order) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", g5Order.getId());
        long o = g5OrderService.count(queryWrapper);
        G5Order o2 = g5OrderService.getOne(queryWrapper);
        //订单状态改为q（x是未付款，y是已付款，n是退款,q是取消）
        if (o != 0) {
            g5Order.setIsOk("q");
            g5OrderService.update(g5Order);
            //修改车票为未付款(一个订单包含多个车票)
            List<G5Ticket> t2 = g5TicketService.queryByOrderId(o2.getId());
            G5Ticket g5Ticket = new G5Ticket();
            G5TicketSite g5TicketSite = new G5TicketSite();
            for (int i = 0; i < t2.size(); i++) {
                g5Ticket.setId(t2.get(i).getId());
                g5Ticket.setIsPay("n");
                //g5Ticket.setReTicket("x");
                g5TicketService.update(g5Ticket);
                //修改具体时间车票座位中间表的座位状态
                g5TicketSite.setId(t2.get(i).getTimeSeatId());
                g5TicketSite.setSiteStatus("y");
                g5TicketSiteService.update(g5TicketSite);
            }
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "请勿重复取消！");
    }

    /**
     * 根据用户id查询已经支付订单（有支付时间）
     * （可分页）
     *
     * @return
     */
    @RequestMapping("/list_isPay")
    public ResponseResult<PageInfo<G5Order>> orderIsPay(@RequestBody @Validated OrderPageVO orderPageVO) {
        Integer userId = orderPageVO.getG5Order().getUserId();
        PageInfo<G5Order> pageInfo = new PageInfo<>();
        pageInfo = g5OrderService.findOrderIsPay(userId, orderPageVO.getPageNum(), orderPageVO.getPageSize());
        return new ResponseResult<>(Code.SUCCESS, "", pageInfo);
    }

    /**
     * 根据用户id查询已经支付订单（没有支付时间）
     * （可分页）
     *
     * @return
     */
    @RequestMapping("/list_isNotPay")
    public ResponseResult<PageInfo<G5Order>> orderIsNotPay(@RequestBody @Validated OrderPageVO orderPageVO) {
        Integer userId = orderPageVO.getG5Order().getUserId();
        PageInfo<G5Order> pageInfo = new PageInfo<>();
        pageInfo = g5OrderService.findOrderIsNotPay(userId, orderPageVO.getPageNum(), orderPageVO.getPageSize());
        return new ResponseResult<>(Code.SUCCESS, "", pageInfo);
    }

    /**
     * 根据用户id查询取消的订单
     *
     * @param orderPageVO
     * @return
     */
    @RequestMapping("/list_cancel")
    public ResponseResult<PageInfo<G5Order>> orderCancel(@RequestBody @Validated OrderPageVO orderPageVO) {
        Integer userId = orderPageVO.getG5Order().getUserId();
        PageInfo<G5Order> pageInfo = new PageInfo<>();
        pageInfo = g5OrderService.findOrderCancel(userId, orderPageVO.getPageNum(), orderPageVO.getPageSize());
        return new ResponseResult<>(Code.SUCCESS, "", pageInfo);
    }

    /**
     * 根据用户id查询退款的订单
     * @param orderPageVO
     * @return
     */
    @RequestMapping("/list_refund")
    public ResponseResult<PageInfo<G5Order>> orderRefund(@RequestBody @Validated OrderPageVO orderPageVO){
        Integer userId = orderPageVO.getG5Order().getUserId();
        PageInfo<G5Order> pageInfo = new PageInfo<>();
        pageInfo = g5OrderService.findOrderRefund(userId, orderPageVO.getPageNum(), orderPageVO.getPageSize());
        return new ResponseResult<>(Code.SUCCESS, "", pageInfo);
    }


}
